import { defineStore } from 'pinia'
import { userAPI } from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    isLoggedIn: false,
    permissions: [],
    preferences: {
      theme: 'light',
      language: 'zh-CN',
      notifications: {
        health: true,
        medication: true,
        schedule: true,
        system: true
      }
    }
  }),

  getters: {
    // 获取用户姓名
    userName: (state) => state.userInfo?.name || '用户',
    
    // 获取用户头像
    userAvatar: (state) => state.userInfo?.avatar || '/default-avatar.png',
    
    // 获取用户角色
    userRole: (state) => state.userInfo?.role || 'user',
    
    // 是否为管理员
    isAdmin: (state) => state.userInfo?.role === 'admin',
    
    // 是否有特定权限
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    }
  },

  actions: {
    // 登录
    async login(credentials) {
      try {
        const response = await userAPI.login(credentials)
        
        this.token = response.token
        this.userInfo = response.userInfo
        this.isLoggedIn = true
        this.permissions = response.permissions || []
        
        // 存储到localStorage
        localStorage.setItem('token', this.token)
        localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
        
        return response
      } catch (error) {
        throw error
      }
    },

    // 登出
    logout() {
      this.token = null
      this.userInfo = null
      this.isLoggedIn = false
      this.permissions = []
      
      // 清除localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    },
  },

  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['userInfo', 'token', 'isLoggedIn', 'preferences']
  }
})